<template>
  <div name="消息发送" class="gl_contentBox gl_heightFull">
    <!-- 操作按钮 -->
    <el-row :gutter="20" class="gl_mb_15">
      <el-col :span="24">
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="openAddDialog()">新增教练</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" style="width: 100%" class="gl_table_noBorder" :border="false" stripe size="mini">
      <!-- 通用-序号 -->
      <el-table-column type="index" label="序号" align="center" width="50" />
      <el-table-column prop="imagePath" label="教练头像" align="center">
        <template slot-scope="{row}">
          <div class="cover_img">
            <img :src="getStaticFileUrl(row.imagePath)" alt="">
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="教练姓名" align="center">
        <template slot-scope="{row}">
          <div>{{ row.name }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="level" label="教练级别" align="center">
        <template slot-scope="{row}">
          <div>{{ row.level }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="eventName" label="运动项目" align="center">
        <template slot-scope="{row}">
          <div>{{ row.eventName ? row.eventName : '' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="experienced" label="教练简介" align="center">
        <template slot-scope="{row}">
          <div>{{ row.experienced ? row.experienced : '' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="creationTime" label="编辑时间" align="center">
        <template slot-scope="{row}">
          <div>{{ row.creationTime }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="operating" label="操作" align="center" width="200">
        <template slot-scope="{row,$index}">
          <el-button type="text" size="mini" @click="publishItem(row)">
            <span class="gl_color_warning">{{ row.isPublish ? '取消发布' : '发布' }}</span>
          </el-button>
          <el-button type="text" size="mini" @click="openAddDialog(row)">编辑</el-button>
          <el-button type="text" size="mini" @click="topItem(row)">
            <span class="gl_color_warning">{{ row.isTop ? '取消置顶' : '置顶' }}</span></el-button>
          <el-button type="text" size="mini" @click="deleteItem(row,$index)">
            <span class="gl_color_error">删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-row class="gl_pt_15" style="text-align: right;">
      <el-pagination
        :current-page="qo.Page"
        :page-size="qo.MaxResultCount"
        :total="total"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </el-row>

    <!-- 新建/编辑弹窗 -->
    <el-dialog
      class="gl_dialog_TitleLine"
      width="800"
      :title="type === 'edit' ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form
        ref="formInput"
        :model="formInput"
        :rules="creatCoach_rules"
        label-width="80px"
        size="mini"
      >
        <el-row>
          <el-col :span="8">
            <el-row>
              <el-form-item label-width="20px" align="center" prop="imagePath">
                <el-input v-show="false" v-model.trim="formInput.imagePath" />
                <el-dialog class="gl_dialog_TitleLine" width="880px" title="上传图片" :append-to-body="true" :visible.sync="photoCropperVisible" :close-on-click-modal="false" :close-on-press-escape="false">
                  <photo-cropper ref="photoCropper" :photograph="false" :action="action" :option="photoCropperOption" height="375px" @photoCropperSave="photoCropperSave" />
                </el-dialog>
                <div class="upload_game_img" :class="formInput.imagePath ? '' : 'no_pointer'" @click="openPhotoCropper">
                  <img v-if="formInput.imagePath" class="show_img" :src="getStaticFileUrl(formInput.imagePath)">
                  <i v-else class="el-icon-plus" />
                </div>
              </el-form-item>
            </el-row>
          </el-col>
          <el-col :span="16">
            <el-row>
              <el-col :span="24">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="formInput.name" placeholder="请输入姓名" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="国籍" prop="nationality">
                  <el-select v-model="formInput.nationality" placeholder="请选择国籍" filterable size="mini" style="width: 100%" @change="onChangeNationality">
                    <el-option v-for="item in dict.country" :key="item.code" :label="item.value" :value="item.code" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="教练级别" prop="level">
                  <el-input v-model="formInput.level" placeholder="请输入教练级别" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="运动项目" prop="eventName">
                  <el-input v-model="formInput.eventName" placeholder="请输入运动项目" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="身高" prop="height">
                  <el-input v-model="formInput.height" type="number" placeholder="请输入身高" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="体重" prop="weight">
                  <el-input v-model="formInput.weight" type="number" placeholder="请输入体重" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="年龄" prop="age">
                  <el-input v-model.trim="formInput.age" :min="1" type="number" placeholder="请输入年龄" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="运动生涯" prop="experienced">
                  <el-input v-model="formInput.experienced" type="textarea" :rows="5" :min="0" maxlength="100" placeholder="请输入报名条件" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" :loading="btnLoading" @click="submitConfirm()">确认</el-button>
        <el-button size="mini" :loading="btnLoading" type="primary" @click="submitConfirm(true)">发布</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { FormatDate } from '@/lib';
import photoCropper from '@/components/PhotoCropper';
import {
  api_GET_ClubTeachingCoach,
  api_POST_ClubTeachingCoach, // 创建教练
  api_PUT_ClubTeachingCoachId, // 修改教练
  api_DELETE_ClubTeachingCoachId, // 删除
  api_POST_ClubTeachingCoachIdPublish, // 发布
  api_POST_ClubTeachingCoachIdTop
} from '@/extend/api/hallswaggerApi/app.js';
import { Api_GET_ClubTeachingCoachQO, CreateTeachingCoachInput } from '@/lib/form/hall/swaggerForm';
import { CreatCoach_rules } from '@/lib/validate/mobileConfig/index.js';
export default {
  components: {
    photoCropper
  },
  data () {
    return {
      qo: new Api_GET_ClubTeachingCoachQO(),
      tableData: [],
      loading: false,
      total: 0,
      // 新增
      type: '',
      dialogVisible: false,
      btnLoading: false,
      formInput: new CreateTeachingCoachInput(),
      creatCoach_rules: new CreatCoach_rules(),
      // 上传照片
      photoCropperVisible: false, // 上传图片窗口的显示与隐藏
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`, // 图片上传地址
      photoCropperOption: {
        img: '',
        autoCropWidth: '150px',
        autoCropHeight: '180px',
        enlarge: 1,
        fixedNumber: [150, 180]
      }
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    })
  },
  watch: {
    dialogVisible: {
      handler(val) {
        if (!val) {
          this.formInput = new CreateTeachingCoachInput();
          this.$refs['formInput'].resetFields();
        }
      }
    }
  },
  created() {
    this.getDict();
    this.getDictByType(['district']);
    this.getPageList();
  },
  methods: {
    // 若没有字典信息，外部可直接调用方法获取字典数据
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    getPageList(page) {
      this.qo.Page = page || 1;
      this.qo.SkipCount = (this.qo.Page - 1) * this.qo.MaxResultCount;
      this.qo.IsTop = null;
      this.qo.IsPublish = null;
      this.loading = true;
      api_GET_ClubTeachingCoach(this.qo).then(
        res => {
          if (res) {
            this.tableData = res.items || [];
            this.tableData.map(item => {
              item.creationTime = item.creationTime ? FormatDate(item.creationTime, 'yyyy-MM-dd HH:mm:ss') : '';
            });
            console.log('kdkd', this.tableData);
            this.total = res.totalCount;
            this.loading = false;
          }
        },
        error => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
          this.loading = false;
        }
      );
    },
    // 打开弹窗
    openAddDialog(row) {
      if (row) {
        this.type = 'edit';
        this.formInput = row;
      } else {
        this.type = 'add';
      }
      this.dialogVisible = true;
      this.dialogVisible = true;
      console.log('row', row);
    },
    // 确认新建
    submitConfirm(flag) {
      this.btnLoading = true;
      this.$refs['formInput'].validate((valid) => {
        if (valid) {
          if (flag) {
            this.formInput.isPublish = true;
          }
          if (this.type === 'edit') {
            this.updateCoach();
          } else {
            this.createCoach();
          }
        } else {
          this.btnLoading = false;
        }
      });
    },
    createCoach() {
      console.log('this.forminput', this.formInput);
      api_POST_ClubTeachingCoach(this.formInput).then(res => {
        this.$message({
          type: 'success',
          message: '创建成功'
        });
        this.btnLoading = false;
        this.dialogVisible = false;
        this.getPageList();
      }).catch(error => {
        this.btnLoading = false;
        this.$message({ type: 'error', message: error.error.message });
      });
    },
    updateCoach() {
      api_PUT_ClubTeachingCoachId(this.formInput.id, this.formInput).then(res => {
        this.$message({
          type: 'success',
          message: '更新成功'
        });
        this.btnLoading = false;
        this.dialogVisible = false;
        this.getPageList();
      }).catch(error => {
        this.btnLoading = false;
        this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 删除
    deleteItem(row, index) {
      this.$confirm(`您确定要删除该教练吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_ClubTeachingCoachId(row.id).then(
            () => {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getPageList();
            },
            error => {
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            }
          );
        });
    },
    // 发布
    publishItem(row) {
      const msg = row.isPublish ? '已取消发布' : '发布成功';
      api_POST_ClubTeachingCoachIdPublish(
        row.id,
        {
          isPublish: !row.isPublish
        }
      ).then(
        res => {
          this.$message({
            message: msg,
            type: 'success'
          });
          this.getPageList();
        },
        error => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 置顶
    topItem(row) {
      console.log(row);
      const msg = row.isTop ? '已取消置顶' : '置顶成功';
      api_POST_ClubTeachingCoachIdTop(
        row.id,
        { isTop: !row.isTop }
      ).then(
        res => {
          this.$message({
            message: msg,
            type: 'success'
          });
          this.getPageList();
        },
        error => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 点击打开照片裁剪窗口
    openPhotoCropper() {
      console.log('openPhotoCropper', this.formInput);
      if (this.formInput['imagePath']) {
        this.$set(this.photoCropperOption, 'img', this.getStaticFileUrl(this.formInput['imagePath']));
      }
      this.photoCropperVisible = true;
    },
    // 点击保存照片裁剪窗口
    photoCropperSave (uploadImg) {
      this.$refs.photoCropper.upload().then(res => {
        this.$set(this.formInput, 'imagePath', res.tempUrl);
        this.photoCropperVisible = false;
      });
    },
    onChangeNationality () {
      this.formInput.national = '';
    },
    // 根据code在相应字典中寻找数据
    findDictDataByCode (dictKey, code) {
      const _dict = this.dict[dictKey];
      if (_dict) {
        return _dict.find(item => item.code === code) || {};
      } else {
        console.log('findDictDataByCode -> findDictDataByCode: ' + dictKey + ', 未找到字典数据.');
        return {};
      }
    },
    // 分页
    sizeChange(MaxResultCount) {
      this.qo.MaxResultCount = MaxResultCount;
      this.getPageList();
    },
    pageIndexChange(currentPage) {
      this.getPageList(currentPage);
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    }
  }
};
</script>

<style lang="scss" scoped>
  .upload_game_img.no_pointer {
    cursor: default;
  }
  .upload_game_img {
    width: 150px;
    height: 180px;
    line-height: 205px;
    text-align: center;
    font-size: 20px;
    border: 1px dotted #DCDFE6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
    position: relative;
    margin: 10px 0;
  }
  .upload_game_img .show_img {
    max-width: 100%;
    max-height: 100%;
    border-radius: 4px;
    vertical-align: middle;
  }
.cover_img {
  width: 50px;
  height: 60px;
  margin: auto;
}

.cover_img img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  vertical-align: middle;
}
</style>

